﻿using UnityEngine;
using System.Collections;

/// <summary>
/// Script used to procedurally color the individual blocks in the level.
/// </summary>
public class ColorizeSubObjects : MonoBehaviour {
	
	/// <summary>
	/// The color to assign to goal blocks.
	/// </summary>
	public Color GoalColor;
	
	// Use this for initialization
	void Start () {
		// Find all the renderers in the hierarchy
		Renderer[] renderers = GetComponentsInChildren<Renderer>();
		
		// Each renderer attached to a GameObject that also has a GoalBox instance attached will have its material set to the GoalColor
		SetWithComponent<GoalBox>(renderers, GoalColor);
	}
	
	/// <summary>
	/// Sets the colors of all the renderers supplied as parameter to independently random colors.
	/// </summary>
	/// <param name='renderers'>
	/// List of renderers to which random colors should be assigned.
	/// </param>
	void RandomizeColors(Renderer[] renderers)
	{
		foreach (Renderer objectRenderer in renderers)
		{
			float r = RandomUnit();
			float g = RandomUnit();
			float b = RandomUnit();
			float a = 1F;
			objectRenderer.material.SetColor("_Color", new Color(r, g, b, a));
		}
	}
	
	/// <summary>
	/// Given a list of renderers and a color to assign, finds all attached instances of the supplied type and assigns to them the given color.
	/// </summary>
	/// <param name='renderers'>
	/// List of renderers through which to search.
	/// </param>
	/// <param name='color'>
	/// Color to assign to renderers which also have an instance of the supplied type attached.
	/// </param>
	/// <typeparam name='T'>
	/// Type parameter indicating what Component sub-type this method should search for when determining when to assign the given color.
	/// </typeparam>
	void SetWithComponent<T>(Renderer[] renderers, Color color) where T : Component
	{
		foreach (Renderer objectRenderer in renderers)
		{
			if (objectRenderer.GetComponent<T>() != null)
				objectRenderer.material.SetColor("_Color", color);
		}
	}
	
	/// <summary>
	/// Produces a random float on the non-negative unit interval.
	/// </summary>
	/// <returns>
	/// A random float on the non-negative unit interval.
	/// </returns>
	float RandomUnit()
	{
		return Random.Range(0F, 1F);
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}
